<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Lib\JwtAuth;

class ApiAuth3
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        global $__MINI_GLOBAL_DEVICE__, $__MINI_GLOBAL_IP__,$__MINI_GLOBAL_PLATFORM__,$__MINI_GLOBAL_TENANT_ID__,$__MINI_GLOBAL_TENANTS_ARR__,$__MINI_GLOBAL_SCENE__,$__MINI_GLOBAL_FRONT_VERSION__;
        if(_empty_($__MINI_GLOBAL_IP__)){
            if(_empty_($request->header('X-Forwarded-For',''))){
                $__MINI_GLOBAL_IP__ = $request->ip();
            }else{
                $__MINI_GLOBAL_IP__ = $request->header('X-Forwarded-For','');
            }
        }

        $__MINI_GLOBAL_TENANT_ID__ = $request->header('tenant',0);
        if(!in_array($__MINI_GLOBAL_TENANT_ID__, $__MINI_GLOBAL_TENANTS_ARR__)){
            $__MINI_GLOBAL_TENANT_ID__ = 0;
        }

        $__MINI_GLOBAL_DEVICE__ = $request->header('device','mp');
        $__MINI_GLOBAL_PLATFORM__ = $request->header('platform','android');
        $__MINI_GLOBAL_SCENE__ = $request->header('scene', 0);
        $__MINI_GLOBAL_FRONT_VERSION__ = $request->header('version', '1.2.2.16');

        $token = $request->header('token','');
        if(_empty_($token)){
            $token = $request->token;
        }

        if(!_empty_($token) && JwtAuth::verifyToken($token)){
            $uid = JwtAuth::getUserId($token,'uid');
            $request->merge(['uid' => $uid]);

            if($uid > 0){
                global $__MINI_GLOBAL_CURRENT_USER_ID__, $__MINI_GLOBAL_IS_ADMIN_SUPER__;
                $__MINI_GLOBAL_CURRENT_USER_ID__ = $uid;
                if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                    if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0 && in_array($__MINI_GLOBAL_CURRENT_USER_ID__, explode(',', env('APP_SUPER_ADMIN_USER_ID', '')))){
                        $__MINI_GLOBAL_IS_ADMIN_SUPER__ = true;
                    }
                }
            }
        }else{
            $request->except(['uid', 'player']);
        }
        return $next($request);
    }
}
